# !/usr/bin/env python
# -*-coding:utf-8 -*-

"""
# File       : process_status_view.py
# Time       ：2023/11/2 15:33
# Author     ：YangYong
# version    ：python 3.10
# Description：流程运行状态统计
"""
from flask_restx import Resource, fields
from sqlalchemy import case, func

from apis.data_screen import data_screen_ns
from apis.data_screen.schema.process_status_schema import ProcessStatusSchema
from apis.orderlines.models import ProcessInstance
from orderlines.utils.orderlines_enum import ProcessStates
from public.api_utils.api_decorator import handle_api_error
from public.base_model import db
from public.base_response import generate_response, MarshalModel

process_status = {
    'name': fields.String(description='流程状态'),
    'value': fields.Integer(description='流程数量'),
    'percentage': fields.String(description='占比'),
}

process_status_marshal = MarshalModel('process_status', data_screen_ns)


class ProcessStatusView(Resource):
    url = '/process_status'

    def __init__(self, *args, **kwargs):
        super(ProcessStatusView, self).__init__(*args, **kwargs)
        self.total = 0
        self.keys = ['运行成功', '运行失败', '运行超时', '运行停止', '运行排队', '运行中']

    def get_process_status(self):

        spot_case = case(
            (ProcessInstance.process_status == ProcessStates.green.value, '运行成功'),
            (ProcessInstance.process_status == ProcessStates.red.value, '运行失败'),
            (ProcessInstance.process_status == ProcessStates.yellow.value, '运行停止'),
            (ProcessInstance.process_status == ProcessStates.grey.value, '运行排队'),
            (ProcessInstance.process_status == ProcessStates.blue.value, '运行中'),
            (ProcessInstance.process_status == ProcessStates.orange.value, '运行超时'),
            else_='未知状态'
        ).label('name')

        objs = db.session.query(
            spot_case, func.count(ProcessInstance.id).label('value')
        ).filter(ProcessInstance.active == 1).group_by(spot_case).all()
        info = ProcessStatusSchema().dump(objs, many=True)
        info = [item for item in info if item.get('name')]
        exist_keys = [item.get('name') for item in info if item.get('name') in self.keys]
        not_exist_keys = [item for item in self.keys if item not in exist_keys]
        for key in not_exist_keys:
            info.append({'name': key, 'value': 0})

        info.sort(key=lambda item: item.get('name'))
        return info

    @handle_api_error()
    @data_screen_ns.doc(description='流程运行状态统计')
    @data_screen_ns.marshal_with(process_status_marshal.list_response(process_status, True, False))
    def get(self):
        """流程运行状态统计"""
        response_data = list()

        info = self.get_process_status()
        for item in info:
            self.total = self.total + item.get('value') or 0
        for item in info:
            temp = {
                'name': item.get('name'),
                'value': item.get('value'),
                'percentage': f"{round(item.get('value') / self.total * 100)}%" if self.total != 0 else '0',
            }
            response_data.append(temp)
        return generate_response(response_data)
